<script setup>
/**
 * & 文件引入区域
 */
import { ref, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { debounce } from "@/utils/debounce"
import {
  generateUnpaidItemOrder,
  generateUnpaidOrderByPi,
} from "@/server/api/itemApi";
import {
  deleteBuyerDataByIdAPI,
  faultAddressAIP,
  selectAllAddressAPI,
  updateBuyerDataByIdAPI,
} from "@/server/api/BuyerData";
import { generateUnpaidShopOrder } from "@/server/api/shopApi";

import { ToastFun } from "@/hook/toast";
import { getJWTFun } from "@/hook/jsrsasign";

import { orderStatus } from "@/stores/payStore";
import { useUseStore } from "@/stores/user";
import { countryList } from "@/data/countryList";

import { getLogisticsQuotation } from "@/server/api/logisticsQuotation";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const router = useRouter();
const route = useRoute();

/**
 * checked：控制支付方式
 * true为积分支付
 * false为pi支付
 */
let checked = ref(true);
let showBottom = ref(false); // 地址选择弹出层
let addressList = ref(); // 获取的地址列表
let selectAddress = ref(); // 选择的地址，默认第一个
let addressId = ref(); // 选择的地址Id
let unPaidOrderReq = ref(); // 生成未支付订单的请求头
let userId = useUseStore().userId; // 获取userId
let price = ref(0); // 渲染到页面的价格，只用于网店订单
const sumCount = ref(1)
const commoditySpecification = ref()

let postlist = ref([]); //获取快递名称
let postage = ref([]); //获取快递资金
let selectedDeliveryWay = ref(null); //获取选择器的值
let totalPost = ref(0); //存取总的邮费
let toCountryName = ref(null); //获取选择的国家名字
let tocountryEame = ref(null); //获取国家的英文名
let isCountry = ref(false); //判断国家的选择状态
let isPost = ref(false); //判断邮费的状态
let toCountryCode = ref(); //获取国家列表的code
let deaultImg = ref(null); //获取国旗的图片
let packageWeight = ref(500); //获取运输的货物重量,默认为500
//let isWarn = ref(false); //提示无重量或者无快递方式

// 将获得的首重续重以及额外的费用拆分开，并拿来计算得出最终的总邮费
let firstWeightFee = ref();
let continueWeightFee = ref();
let firstWeight = ref();
let firstWeightPrice = ref();
let continueWeight = ref();
let continueWeightPrice = ref();
let AddedServicesFee = ref();
let AddedServicesPrice = ref();

const id = ref(useUseStore().countryCode); //获取topBar传过来的参数

/**
 * & 函数区
 */
//获得后端对应的选项列表里的数据

console.log(id, "idididid");

const getInfo = async (img, country) => {
  deaultImg = img;
  toCountryCode = country.countryCode;
  // console.log(toCountryCode)
  tocountryEame = country.countryEName;
  //根据国家的代号名字来查找对应的快递名称
  toCountryName = country.countryName;
  console.log(toCountryName);
  const res = await getLogisticsQuotation(toCountryCode);
  console.log(res, "res");
  postlist.value = res.data;
  console.log(postlist.value, "postlist");
};


const totalPrice = computed(() => {
  // 如果价格为空或者不是有效数字，返回 0
  // const unitPrice = parseFloat(price.value) || 0;
  return (orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].price * orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].number).toFixed(2)
});



const totalPi = computed(() => {
  // 如果价格为空或者不是有效数字，返回 0
  // const unitPrice = parseFloat(price.value) || 0;
  return (orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].piPrice * orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].number).toFixed(2)
});


const isWarn = computed(() => {
  if (packageWeight.value == 0) {
    ToastFun("", { msg: t("MakesureOrder.weight2") });
    if (postlist.value.length == 0) {
      ToastFun("show", {
        msg: t("order.selectAddress2"),
      });
      router.push("/AddNewAddress");
    }
  } else {
    ToastFun("", {});
    // router.back();
  }
});

//改变根据不同的选项计算不同的邮费
const changePost = () => {
  isPost.value = true;

  //获取对应的邮费数据
  postage.value = postlist.value.filter(
    (item) => item.businessProducts === selectedDeliveryWay.value
  );
  console.log(postage.value[0], "postage");
  firstWeightFee.value = postage.value[0].firstWeightTariff;
  if (firstWeightFee.value !== null) {
    //将获取到的首重的重量和价钱分开来
    const match1 = firstWeightFee.value.match(/([\d.]+)\s*eCNY\/(\d+)\s*g/);
    if (match1.value !== null) {
      firstWeightPrice.value = match1[1];
      firstWeight.value = match1[2];
      console.log(firstWeightPrice, 1111);
      console.log(firstWeight);
    }
  }

  continueWeightFee.value = postage.value[0].wrenewalUnitPrice;
  // 将续重的重量跟价钱分开来
  if (continueWeightFee.value !== null) {
    const match2 = continueWeightFee.value.match(/([\d.]+)\s*eCNY\/(\d+)\s*g/);
    console.log(111111111);
    console.log(match2, "ssssssss");
    if (match2 !== null) {
      continueWeightPrice.value = match2[1];
      continueWeight.value = match2[2];
      console.log(22222);
      console.log(continueWeight, 2121);
    }
  }

  AddedServicesFee.value = postage.value[0].valueAddedServices;
  if (AddedServicesFee.value !== null) {
    const match3 = AddedServicesFee.value.match(/\d+(\.\d+)?/);
    if (match3.value !== null) {
      AddedServicesPrice.value = match3[0];
      console.log(AddedServicesPrice, "ahahahah");
    }
  }

  //计算总邮费
  totalPost = computed(() => {
    let total = 0;
    if (
      selectedDeliveryWay.value !== null &&
      firstWeightFee.value !== null &&
      AddedServicesFee.value !== null &&
      continueWeightFee.value !== null
    ) {
      if (Number(packageWeight.value) === 0 || postlist.value.length === 0) {
        total = 0;
      } else if (Number(packageWeight.value) <= Number(firstWeight.value)) {
        total =
          Number(firstWeightPrice.value) + Number(AddedServicesPrice.value);
      } else if (
        Number(packageWeight.value) > Number(firstWeight.value) &&
        Number(packageWeight.value) - Number(firstWeight.value) <
        Number(continueWeight.value)
      ) {
        total =
          Number(firstWeightPrice.value) +
          Number(continueWeightPrice.value) +
          Number(AddedServicesPrice.value);
      } else if (
        Number(packageWeight.value) - Number(firstWeight.value) >=
        Number(continueWeight.value)
      ) {
        total =
          Number(firstWeightPrice.value) +
          Number(continueWeightPrice.value) *
          Math.floor(
            (Number(packageWeight.value) - Number(firstWeight.value)) /
            Number(continueWeight.value)
          ) +
          Number(AddedServicesPrice.value);
      }
    }
    return Number(total.toFixed(2));
  });
  console.log(totalPost.value, "total");
};



// 跳转支付页面
const toItemPay = () => {
  // 如果为真即积分支付
  if (checked.value) {
    // ! 判断如果类型为网店类型，则调用网店的订单接口
    unPaidItemOrderFun();
  }
  // 否则为PI支付
  else {
    ItemOrderByPIFun();
  }

};

debounce(toItemPay, 1000)

// 获取用户地址列表
const getAllAddress = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await selectAllAddressAPI(userId);

  if (data.code === 200) {
    if (data.data.length > 0) {
      ToastFun("", {});
      addressList.value = data.data;
      selectAddress.value = addressList.value[0];
      addressId.value = addressList.value[0].buyerDataId;

      console.log("地址列表", addressList.value);
    } else {
      ToastFun("show", { msg: t("item.details.noAddress") });
      router.back();
    }
  } else {
    ToastFun("", {});
    router.back();
  }
  // console.log("选择的地址", selectAddress.value);
};

// 选择地址方法
const selectAddFun = (id) => {
  // 隐藏弹框
  addressId.value == id
    ? (showBottom.value = true)
    : (showBottom.value = false);

  // 控制样式
  addressId.value = id;
  modifyAddress(id); //传参
  // 找到下标
  let index = addressList.value.findIndex((item) => item.buyerDataId == id);
  // 赋值选择的地址，以渲染到页面
  selectAddress.value = addressList.value[index];
  console.log("选择的地址", selectAddress.value);
};

// 生成网店商品未支付订单 (积分支付)
const unPaidItemOrderFun = async () => {
  try {
    orderStatus().itmeOrderReq.buyerDataId = addressId.value;
    let token = getJWTFun(orderStatus().itmeOrderReq);
    orderStatus().payType = "item";
    ToastFun("Loading", { duration: 0 });
    let res = await generateUnpaidItemOrder(token);
    if (res.data.code == 200) {
      let orderIdArray = res.data.data;
      let { uid } = orderStatus().itmeOrderReq;
      orderStatus().itmePayReq = {
        uid,
        orderIdArray,
        payPointSum: totalPrice.value.toString(),
      };
      ToastFun("show", { msg: res.data.msg });
      router.push({ path: "/itemPay" });
    } else {
      ToastFun("fail", { msg: res.data.msg });
    }
  } catch (error) {
    ToastFun("fail", { msg: t("item.details.NetworkError") });
  }
};

// 生产网店商品未支付订单 (PI支付)
const ItemOrderByPIFun = async () => {
  ToastFun("show", { msg: t("item.details.NoPiPayment") });
  // let { uid, itemOrderDetailDTOList } = unPaidOrderReq.value; // 解构出所需的成员
  // // 重新生成一个请求体
  // let unPaidPIOrderReq = {
  //   uid,
  //   paymentId: 1,
  //   buyerDataId: addressId.value, // 添加地址id到请求体中
  //   itemOrderDetailDTO: itemOrderDetailDTOList[0],
  // };

  // let token = getJWTFun(unPaidPIOrderReq); // 生成token

  // try {
  //   ToastFun("Loading", { duration: 1000 });
  //   let { data } = await generateUnpaidOrderByPi(token); // 请求接口
  //   // console.log(unPaidPIOrderReq);

  //   if (data.code == 200) {
  //     // 修改状态管理库生成支付订单的请求头
  //     orderStatus().itmePayReq = {
  //       userId,
  //       orderId: data.data,
  //     };

  //     router.push({
  //       path: "/piPayOrder",
  //       query: {
  //         price: price.value,
  //       },
  //     });

  //     ToastFun("", {});
  //   } else {
  //     ToastFun("", {});
  //   }
  // } catch {
  //   ToastFun("", {});
  // }
};


// 监听支付方式选择：checked
watch(
  () => checked.value,
  (newVl) => {
    // 判断用户选择的支付方式，切换订单的价格
    price.value = newVl
      ? unPaidOrderReq.value.itemOrderDetailDTOList[0].price
      : unPaidOrderReq.value.itemOrderDetailDTOList[0].piPrice;
  }
);

onMounted(() => {
  let type = orderStatus().orderType;
  if (type === "item") {
    // 判断订单类型是否为网店，是则获取网店未支付订单的请求头
    unPaidOrderReq.value = orderStatus().itmeOrderReq;
    console.log(unPaidOrderReq.value, "传过来")
    price.value = unPaidOrderReq.value.itemOrderDetailDTOList[0].price;
    console.log(price.value);
    sumCount.value = unPaidOrderReq.value.itemOrderDetailDTOList[0].number;
    commoditySpecification.value = unPaidOrderReq.value.itemOrderDetailDTOList[0].commoditySpecification
    console.log(orderStatus().itmeOrderReq, "数组")
    getAllAddress(); // 获取用户地址列表，实体店商品订单不需要获取地址
  }
});
</script>

<template>
  <div class="contain">
    <!-- 导航栏 -->
    <div class="nav">
      <div class="left" @click="$router.back()">
        <img src="/images/cart/back.png" />
      </div>
      <div class="title">{{ $t("order.confirmOrder") }}</div>
    </div>

    <!-- 商品信息 -->
    <div class="product-information">
      <!-- 商品名 -->
      <div class="name">{{ $route.query.commodityName }}</div>

      <!-- 先判断是否是piftware -->
      <div v-if="id === 'PIFTWARE'">
        <!-- 选择的国家及其对应的邮费-->
        <div class="destination" style="width: 100%; height: 20%" @click="isCountry = !isCountry">
          <div class="pleaseSelect" style="font-size: 10rem; margin-top: 5rem">
            {{ $t("MakesureOrder.toCountry") }}
          </div>
          <div class="toCountry">
            <img :src="deaultImg == null ? `/images/countryImg/China.png` : deaultImg
              " style="width: 50px; height: 30px" />
            <span>{{ tocountryEame == null ? "China" : tocountryEame }}</span>
          </div>
          <div class="destinationcontent">
            <ul v-if="isCountry">
              <li v-for="(country, index) in countryList" :key="index"
                @click="getInfo(`/images/countryImg/` + country.img, country)">
                <img :src="`/images/countryImg/` + country.img" style="width: 50px; height: 30px" v-if="index > 0" />
                <span class="toName" v-if="index > 0">{{
                  country.countryEName
                }}</span>
              </li>
            </ul>
            <!-- <div class="estimatedTimeestimatedTime" style="font-size: 10px;">{{ $t("MakesureOrder.toTheTime") }}:111</div>(不知道数据在哪) -->
          </div>
        </div>

        <!-- 获取运输的重量 -->
        <div class="traffic" style="margin-top: 10px">
          <label>{{ $t("MakesureOrder.weight") }}</label>
          <input v-model="packageWeight" type="number" />
        </div>

        <!-- 运货方式的选择-->
        <div class="postway" style="display: flex; margin-top: 10px">
          <div class="poststyle">{{ $t("MakesureOrder.DeliveryWay") }}</div>
          <select style="width: 200px" v-model="selectedDeliveryWay" @change="changePost()">
            <option v-for="p in postlist" :key="p">
              {{ p.businessProducts }}
            </option>
          </select>
        </div>

        <!-- 邮费结算方式 -->
        <div class="postage" v-if="isPost">
          <div>
            {{ $t("MakesureOrder.FirstWeightTariff") }} : &nbsp;&nbsp;{{
              firstWeightFee
            }}
          </div>
          <div>
            {{ $t("MakesureOrder.WrenewalUnitPrice") }} : &nbsp;&nbsp;{{
              continueWeightFee
            }}
          </div>
          <div>
            {{ $t("MakesureOrder.valueAddedServices") }} : &nbsp;&nbsp;{{
              AddedServicesFee
            }}
          </div>
        </div>
      </div>

      <!-- to地址 -->
      <div class="to" v-if="orderStatus().orderType == 'item' && selectAddress" @click="showBottom = true">
        <div class="title-to cut-txt">{{ $t("order.address") }}</div>

        <div class="text-down">
          <div class="text-to">
            <span>{{ selectAddress.userName }} &nbsp;</span>
            <span>{{ selectAddress.phone }} &nbsp;</span>
            <span>{{ selectAddress.address }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="PointPayment">
      <div class="item">
        <div class="title">{{ $t("order.pointPay") }}</div>
        <div :class="['checkbox', checked ? 'con' : '']" @click="checked = true">
          <img src="/images/Home/check.png" alt="" class="btn" />
        </div>
      </div>

      <div class="item">
        <div class="title">PI</div>
        <div :class="['checkbox', !checked ? 'con' : '']" @click="checked = false">
          <img src="/images/Home/check.png" alt="" class="btn" />
        </div>
      </div>
    </div>

    <!-- 总价 -->
    <div class="GoodsPrice" v-if="
      orderStatus().itmeOrderReq && orderStatus().itmeOrderReq.itemOrderDetailDTOList
      && orderStatus().itmeOrderReq.itemOrderDetailDTOList.length">
      <div class="item">
        {{ $t("order.scheduledInfo") }}
        <span>
          {{ $route.query.commodityName }}
        </span>
      </div>
      <div class="item">
        单价
        <span v-if="checked === true">
          {{ orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].price }}
        </span>
        <span v-else>
          {{ orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].piPrice }}
        </span>
      </div>

      <div class="item">
        数量
        <span>
          <van-stepper v-model="orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].number" integer min="1" max="99" />
        </span>
      </div>

      <div class="item">
        规格
        <span>
          {{ orderStatus().itmeOrderReq.itemOrderDetailDTOList[0].commoditySpecification.join(', ') }}
        </span>
      </div>



      <div class="item" v-if="isPost">
        <div class="postage_title">{{ $t("MakesureOrder.postage") }}</div>
        <span>{{ totalPost }}</span>
      </div>
      <div class="buytip" v-if="isWarn">
        No shipping method available and package weight is null
      </div>
    </div>

    <!-- 合计 -->
    <div class="Total">
      <div>{{ $t("order.total") }}</div>
      <span v-if="checked === true">
        {{ totalPrice }}
      </span>
      <span v-else>
        {{ totalPi }}
      </span>

    </div>

    <!-- 提交订单，跳转支付页面 -->
    <div class="Submit" @click="toItemPay">{{ $t("order.submit") }}</div>

    <!-- 弹出层选择地址 -->
    <div class="popup" v-if="orderStatus().orderType === 'item'">
      <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '45%' }">
        <ul class="addersList">
          <li :class="[item.buyerDataId == addressId ? 'border' : '']" @click="selectAddFun(item.buyerDataId)"
            v-for="item in addressList" :key="item.buyerDataId">
            <p class="ellipsis-2">{{ item.address }}</p>

            <div class="footer_en">
              <div class="info">
                <div class="name">{{ item.userName }}</div>
                <div class="date">{{ item.phone }}</div>
              </div>
              <div class="update" @click="modAddress(index)">
                {{ $t("me.modify") }}
              </div>
            </div>
          </li>
        </ul>
      </van-popup>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 容器
.contain {
  width: 100vw;
  min-height: 100vh;
  background-color: rgba(235, 236, 237, 1);
  font-family: "PingFang SC";

  padding-top: 60rem;
  box-sizing: border-box;
}

// 导航栏
.nav {
  padding: 16rem 16rem;

  display: flex;
  align-items: center;

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  background-color: rgba(235, 236, 237, 1);

  .left {
    display: flex;
    align-items: center;
    justify-content: center;

    width: 24rem;
    height: 24rem;
    line-height: 24rem;

    img {
      width: 6rem;
      height: 12rem;
    }
  }

  .title {
    height: 28rem;
    margin: 0 20rem;
    font-size: 20rem;
    font-weight: 500;
    line-height: 28rem;
    text-align: center;
  }
}

.product-information {
  background-color: #fff;
  border-radius: 12rem;
  font-size: 16rem;
  padding: 12rem 12rem 10rem;
  margin: 12rem 16rem;

  .name {
    max-width: 309rem;
    max-height: 48rem;

    font-size: 20rem;
    font-weight: 500;
    line-height: 28rem;
    color: rgba(51, 51, 51, 1);

    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;

    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .to {
    display: flex;
    font-size: 12rem;
    margin: 55rem 0 18rem;
    align-items: center;

    .title-to {
      max-width: 50rem;
      color: #ccc;
      padding-left: 3rem;
    }

    .text-down {
      font-size: 14rem;
      color: #666;
      margin-left: 12rem;

      .text-to {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .seller {
        display: flex;
        font-size: 14rem;

        .sellphome {
          margin-top: 3rem;
          margin-left: 7rem;
          font-weight: 600;
        }
      }
    }
  }
}

.PointPayment {
  padding: 10rem 0;
  margin: 12rem 16rem;
  border-radius: 12rem;
  background: #fff;

  >.item {
    height: 50rem;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      margin: 0 12rem;
      font-size: 16rem;
      font-weight: 500;
      color: rgba(51, 51, 51, 1);
    }

    >.checkbox {
      width: 14rem;
      height: 14rem;
      margin: 0 12rem;

      border: 1rem solid #c9c9c9;
      border-radius: 50%;

      display: flex;
      justify-content: center;
      align-items: center;

      >img {
        width: 8rem;
        margin-top: -2rem;
        display: none;
      }

      &.con {
        background-color: rgba(100, 46, 142, 1);
        border-color: rgba(100, 46, 142, 1);

        >img {
          display: block;
        }
      }
    }
  }
}

.GoodsPrice {
  margin: 12rem 16rem;
  padding: 16rem 12rem;

  border-radius: 12rem;
  background: rgba(255, 255, 255, 1);

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;

    padding: 8rem 0;
    font-size: 16rem;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);

    font-size: 16rem;
    font-weight: 500;
    line-height: 22rem;
    color: #333;
  }

  .buytip {
    color: red;
    font-size: 10rem;
  }
}

.Total {
  height: 66rem;

  border-radius: 12rem;
  background: rgba(255, 255, 255, 1);
  margin: 12rem 16rem;
  padding: 0 12rem;

  font-size: 20rem;
  font-weight: 500;
  color: rgba(51, 51, 51, 1);

  display: flex;
  align-items: center;
  justify-content: space-between;

  position: relative;
  margin-bottom: 60rem;

  span {
    right: 12rem;
    font-size: 24rem;
    color: rgba(100, 46, 142, 1);
  }
}

.Submit {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;

  border-radius: 8rem;
  background: #642e8eff;

  margin: 0 16rem 20rem;

  font-size: 20rem;
  line-height: 50rem;
  text-align: center;
  font-weight: 500;
  color: #fff;
}

.popup {
  :deep(.van-popup) {
    border-radius: 15rem 15rem 0 0;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .addersList {
    padding-top: 20rem;

    li {
      border: 1rem solid #ccc;
      box-sizing: border-box;
      width: 90%;
      background-color: #ffffff;
      border-radius: 10rem;
      margin: 10rem auto 15rem;
      padding: 10rem 15rem;

      p {
        width: 70%;
        font-size: 16rem;
        line-height: 30rem;
      }

      .footer_en {
        display: flex;
        justify-content: space-between;

        .info {
          color: #ccc;
          display: flex;
          font-size: 16rem;
          line-height: 30rem;

          .name {
            margin-right: 10rem;
          }
        }

        .update {
          max-width: 70rem;
          white-space: nowrap;

          color: #fff;
          padding: 0rem 20rem;
          background: #642e8eff;
          border: 2rem solid;
          border-radius: 5rem;
          font-size: 15rem;
        }

        .text_right {
          width: 58rem;
          height: 36rem;
          text-align: center;
          line-height: 36rem;
          white-space: nowrap;
          color: #642e8eff;
          border: 1rem solid;
          border-radius: 5rem;
        }
      }

      &.border {
        border: 1rem solid #642e8eff;
      }
    }
  }
}
</style>
